/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ddd.service;

import com.ddd.context.Parameters;
import com.ddd.entity.User;
import com.ddd.util.HibernateUtil;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class UserService extends BaseService {

    private Parameters para;
    private LogService logService;

    public UserService(HttpServletRequest request) {
        para = new Parameters(request);
        logService = new LogService(request);
    }

    public boolean authorizeBE(String id, String password) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();

        boolean ok;

        try {
            User user = (User) session.load(User.class, id);
            if (user == null || !user.getPassword().equals(password) || !user.getRole().equals("1") || !user.getStatus().equals("1")) {
                ok = false;
            } else {
                ok = true;
                para.setUsername(user.getName());
                para.grantBEAuthorize();
            }
        } catch (Exception e) {
            ok = false;
        }
        tx.commit();
        session.close();

        return ok;
    }

    public boolean authorizeFE(String id, String password) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();

        boolean ok;

        try {
            User user = (User) session.load(User.class, id);
            if (user == null || !user.getPassword().equals(password) || !user.getStatus().equals("1")) {
                ok = false;
            } else {
                ok = true;
                para.setUsername(user.getName());
                para.grantFEAuthorize();
            }
        } catch (Exception e) {
            ok = false;
        }
        tx.commit();
        session.close();

        return ok;
    }
}
